package com.czy.owner.ui.packagecardproject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.czy.owner.R;
import com.czy.owner.alipay.PayResult;
import com.czy.owner.db.UserHelper;
import com.czy.owner.global.Constants;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.Subscribe;
import com.czy.owner.rxbus.ThreadMode;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.setting.ForgetPaidPasswordActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.wxapi.WXPayEntryActivity;
import com.input.password.ui.InputPwdView;
import com.input.password.ui.MyInputPwdUtil;
import com.input.password.ui.PaidErrorDialog;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by wangyang on 2016/6/17.
 * 购买门店套餐
 */
public class BuyStorePackageActivity extends BaseActivity {
    @BindView(R.id.tv_paid_dingjin)
    TextView tvPaidDingjin;//定金金额
    @BindView(R.id.tv_use_yue)
    TextView tvUseYue;//使用余额
    @BindView(R.id.cb_yue)
    CheckBox cbYue;//使用余额CheckBox
    @BindView(R.id.cb_zhifubao)
    CheckBox cbZhiFuBao;//支付宝CheckBox
    @BindView(R.id.cb_weixin)
    CheckBox cbWeiXin;//微信CheckBox
    @BindView(R.id.tv_sdk_paid_tip)
    TextView tvSdkPaidTip;


    private static final int SDK_PAY_FLAG = 1;//支付
    @BindView(R.id.linear_account_bannce)
    LinearLayout linearAccountBannce;
    private String seletPaidType = "aliPay";
    private double realityPaid; //实际支付
    //    private String useStoreBalance = "false";
    private boolean isUseStoreBalance = false;
    private double storeBalance;

    private double totalPrice = 0.00;
    private String servicePackageId = "0";
    private int pushPackageId = 0;
    private int storeId;
    private String numbers = "1";

    private MyInputPwdUtil myInputPwdUtil;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        RxBus.getDefault().post(Constants.BUY_PACKAGE_SUCCESS_CODE, new CommonEvent("购买套餐"));
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        PhoneUtils.ShowToastMessage(BuyStorePackageActivity.this, "支付失败");
                    }
                    break;
                }


            }
        }

    };


    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_buy_store_package;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText(R.string.package_paid);
        RxBus.getDefault().register(this);
        storeId = getIntent().getIntExtra("storeId", 0);
        totalPrice = getIntent().getDoubleExtra("totalPrice", 0.00);
        servicePackageId = getIntent().getStringExtra("servicePackageId");
        pushPackageId = getIntent().getIntExtra("pushPackageId", 0);
        if (!TextUtils.isEmpty(getIntent().getStringExtra("numbers"))) {
            numbers = getIntent().getStringExtra("numbers");
        } else {

        }

        MyLog.e("yang", "购买pushPackageId==" + pushPackageId);
        userPayInfoData();
        getStoreBuyPackageSetting();
        myInputPwdUtil = new MyInputPwdUtil(this);
        myInputPwdUtil.getMyInputDialogBuilder().setAnimStyle(R.style.ActionSheetDialogAnimation);
        myInputPwdUtil.setListener(new InputPwdView.InputPwdListener() {
            @Override
            public void hide() {
                myInputPwdUtil.hide();
            }

            @Override
            public void forgetPwd() {
                startActivity(new Intent(BuyStorePackageActivity.this, ForgetPaidPasswordActivity.class));
            }

            @Override
            public void finishPwd(String pwd) {
                bannceVerifyPayPassword(pwd);
            }
        });
    }

    @Override
    protected void updateViews() {

    }


    private void bannceVerifyPayPassword(String payPassword) {
        String url = Constants.APP_API_BASE + Constants.OWN_VERIFYPAYPASSWORD;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(BuyStorePackageActivity.this).getSession());
        params.addBodyParameter("payPassword", payPassword);
        params.addBodyParameter("userId", UserHelper.getInstance().getUserInfoModel(BuyStorePackageActivity.this).getUserId() + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "111111onSuccess==" + result);
                String exp = JsonUtil.getJsonValuesString(result, "exp");
                boolean flag = JsonUtil.getJsonValuesBoolean(result, "flag");
                int count = JsonUtil.getJsonValuesInt(result, "data");
                if (flag) {
                    myInputPwdUtil.hide();
                    payDepositAmount();
                } else {
                    switch (count) {
                        case 1:
                            myInputPwdUtil.hide();
                            PaidErrorDialog.paidPswErrorDialog(BuyStorePackageActivity.this, myInputPwdUtil);
                            break;
                        case 2:
                            myInputPwdUtil.hide();
                            PaidErrorDialog.paidPswErrorDialog(BuyStorePackageActivity.this, myInputPwdUtil);
                            break;
                        case 3:
                            myInputPwdUtil.hide();
                            PaidErrorDialog.paid30AfterDialog(BuyStorePackageActivity.this, exp);
                            break;
                        case -1:
                            myInputPwdUtil.hide();
                            PaidErrorDialog.paid30AfterDialog(BuyStorePackageActivity.this, exp);
                            break;
                    }
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "onError==" + ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
            }
        });
    }

    private void userPayInfoData() {
        mLoadView.ShowLoadView();
        String url = Constants.APP_API_BASE + Constants.OWN_ORDER_PREBUYPACKAGE;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(BuyStorePackageActivity.this).getSession());
        params.addBodyParameter("storeId", storeId + "");
        MyLog.e("yang", "storeId====" + storeId);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "22222222onSuccess==" + result);
                String data = PhoneUtils.checkResponseFlag(BuyStorePackageActivity.this, result);
                try {
                    if (data != null) {
                        storeBalance = JsonUtil.getJsonValuesDouble(data, "storeBalance");
                        tvPaidDingjin.setText("¥ " + String.format("%.2f", totalPrice));
                        tvUseYue.setText("¥ " + String.format("%.2f", storeBalance));
                        if (storeBalance == 0) {
                            cbYue.setClickable(false);
                        } else {
                            cbYue.setClickable(true);
                        }

                        realityPaid = storeBalance - totalPrice;
                        isUseStoreBalance = realityPaid >= 0;
                    }
                } catch (Exception e) {

                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "onError==" + ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });
    }

    /**
     * 获取门店是否开始余额购买
     */
    private void getStoreBuyPackageSetting() {
        mLoadView.ShowLoadView();
        String url = Constants.APP_API_BASE + Constants.PUB_GETSTOREBUYPACKAGESETTING;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(BuyStorePackageActivity.this).getSession());
        params.addBodyParameter("storeId", storeId + "");
        MyLog.e("hep", "storeId====" + storeId);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("hep", "22222222onSuccess==" + result);
                String data = PhoneUtils.checkResponseFlag(BuyStorePackageActivity.this, result);
                try {
                    if (data != null) {
                        if ("true".equals(data)) {
                            linearAccountBannce.setVisibility(View.VISIBLE);
                        }

                    }
                } catch (Exception e) {

                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "onError==" + ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });
    }

    //余额支付
    @OnClick(R.id.cb_yue)
    public void cbBannce(View view) {
        if (cbYue.isChecked()) {
            if (isUseStoreBalance) {  //当门店余额大于等于实际支付余额时
                cbZhiFuBao.setChecked(false);
                cbWeiXin.setChecked(false);
                cbYue.setChecked(true);
                tvSdkPaidTip.setVisibility(View.GONE);
            } else {
                tvSdkPaidTip.setVisibility(View.VISIBLE);
                tvSdkPaidTip.setText("余额可支付¥" + storeBalance + ",还需第三方支付¥" + String.format("%.2f", Math.abs(realityPaid)));
            }
//            useStoreBalance = "true";
        } else {
            tvSdkPaidTip.setVisibility(View.GONE);
            if (realityPaid >= 0) {  //当门店余额大于等于实际支付余额时
                cbYue.setChecked(true);
            }

//            useStoreBalance = "false";
        }
    }

    //支付宝支付
    @OnClick(R.id.cb_zhifubao)
    public void cbZhiFuBao(View view) {
        if (tvSdkPaidTip.getVisibility() == View.VISIBLE && !cbWeiXin.isChecked()) {
            cbZhiFuBao.setChecked(true);
            return;
        }
        if (cbZhiFuBao.isChecked()) {
            cbWeiXin.setChecked(false);
            seletPaidType = "aliPay";
            if (realityPaid >= 0 && cbYue.isChecked() == true) {
                cbYue.setChecked(false);
            }
        } else {
            seletPaidType = "11";
            cbZhiFuBao.setChecked(true);
        }


    }

    //微信支付
    @OnClick(R.id.cb_weixin)
    public void cbWeiXin(View view) {
        if (tvSdkPaidTip.getVisibility() == View.VISIBLE && !cbZhiFuBao.isChecked()) {
            cbWeiXin.setChecked(true);
            return;
        }
        if (cbWeiXin.isChecked()) {
            cbZhiFuBao.setChecked(false);
            seletPaidType = "wxPay";
            if (realityPaid >= 0 && cbYue.isChecked() == true) {
                cbYue.setChecked(false);
            }
        } else {
            seletPaidType = "22";
            cbWeiXin.setChecked(true);
        }


    }

    //确认支付
    @OnClick(R.id.btn_sure_paid)
    public void btnSurePaid(View view) {
        if (cbYue.isChecked() && totalPrice != 0.00) {
            myInputPwdUtil.show();
        } else {
            payDepositAmount();
        }


    }

    private void payDepositAmount() {
        mLoadView.ShowLoadView();
        String url = Constants.APP_API_BASE + Constants.OWN_ORDER_BUYPACKAGE;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(BuyStorePackageActivity.this).getSession());
        params.addBodyParameter("storeId", storeId + "");
        if (seletPaidType.equals("aliPay") || seletPaidType.equals("wxPay")) {
            params.addBodyParameter("payType", seletPaidType);
        }
        params.addBodyParameter("useStoreBalance", cbYue.isChecked() + "");
        params.addBodyParameter("servicePackageId", servicePackageId);
        params.addBodyParameter("pushPackageId", pushPackageId + "");
        params.addBodyParameter("numbers", numbers);
        MyLog.e("yang", "params==" + params);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "套餐付款onSuccess==" + result);
                String data = PhoneUtils.checkResponseFlag(BuyStorePackageActivity.this, result);
                if (data != null) {
                    if (data.equals("")) {
                        RxBus.getDefault().post(Constants.BUY_PACKAGE_SUCCESS_CODE, new CommonEvent("购买套餐"));
                    } else {
                        if (seletPaidType.equals("aliPay")) {
                            aliPayPaid(data);
                        } else if (seletPaidType.equals("wxPay")) {
                            if (isWXAppInstalledAndSupported()) {
                                WXPayEntryActivity.wxPayPaidStart(BuyStorePackageActivity.this, data, "购买套餐");
                            } else {
                                PhoneUtils.ShowToastMessage(BuyStorePackageActivity.this, getString(R.string.isInstallwx));
                            }
                        }
                    }

                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "套餐付款onError==" + ex.toString());

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });
    }

    //判断是否安装微信客户端
    public boolean isWXAppInstalledAndSupported() {
        IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(WXPayEntryActivity.APP_ID);
        boolean sIsWXAppInstalledAndSupported = msgApi.isWXAppInstalled() && msgApi.isWXAppSupportAPI();
        return sIsWXAppInstalledAndSupported;
    }

    private void aliPayPaid(final String data) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(BuyStorePackageActivity.this);
                // 调用支付接口，获取支付结果
                Map<String, String> result = alipay.payV2(data, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    @Subscribe(code = Constants.BUY_PACKAGE_SUCCESS_CODE, threadMode = ThreadMode.MAIN)
    public void eventBuyPackage(CommonEvent bugPackageEvent) {
        PhoneUtils.ShowToastMessage(BuyStorePackageActivity.this, "购买该套餐成功");
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unRegister(this);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
